# == Schema Information
#
# Table name: strategy_results
#
#  id                         :integer          not null, primary key
#  saler_id                   :integer
#  saler_rate_amount          :float
#  customer_id                :integer
#  customer_discount_amount   :float
#  introducer_id              :integer
#  introducer_rebate_amount   :float
#  remark                     :string
#  order_id                   :integer          not null
#  strategy_id                :integer          not null
#  created_at                 :datetime         not null
#  updated_at                 :datetime         not null
#  saler_director_id          :integer
#  saler_director_rate_amount :float
#  state                      :boolean          default(FALSE)
#  cs_director_id             :integer
#  cs_director_amount         :float
#  operator_id                :integer
#  operator_amount            :float
#  planinger_director_id      :integer
#  planinger_director_amount  :float
#  region_strategy_id         :integer
#

class StrategyResult < ActiveRecord::Base

	ROLE_HASH = {
		saler: 							:saler_rate_amount,
		saler_director: 		:saler_director_rate_amount,
		introducer: 				:introducer_rebate_amount,
		operator: 					:operator_amount,
		cs_director: 				:cs_director_amount,
		planinger_director: :planinger_director_amount
	}

	validates_uniqueness_of :order_id, message: '每条订单最终只能执行一条策略的结果'

	belongs_to :strategy
	belongs_to :region_strategy
	belongs_to :order

	has_many :wallet_logs

	# saler_rate_amount 销售提成
	# saler_director_rate_amount 销售主管提成
	# customer_discount_amount 客户折扣
	# introducer_rebate_amount 介绍人返利
	# cs_director_amount 售后主管提成
	# operator_amount 运营提成(store admin)
	# planinger_director_amount 策划主管提成
	# 售后，策划的提成给到各部门主管，再由各主管分发

	def saler
		User.find_by_id saler_id
	end

	def saler_director
		User.find_by_id saler_director_id
	end

	def customer

	end

	def introducer
		User.find_by_id introducer_id
	end

	def cs_director
		User.find_by_id cs_director_id
	end

	def operator
		User.find_by_id operator_id
	end

	def planinger_director
		User.find_by_id planinger_director_id
	end

	def to_hash
		{
			id: id,
			serial_number: order.serial_number,
			customer_name: order.customer.try(:name),
			saler_name: saler.name,
			saler_mobile: saler.mobile,
			saler_rate_amount: saler_rate_amount
		}
	end

	def total_amount
    ROLE_HASH.values.collect{|ele| self.send(ele.to_sym).to_f}.sum
	end

	# 提成，扣款记录
	def amount_opt(someone, amount, acct)
		WalletLog.create!(
			transfer: 2, state: 1, strategy_result_id: id,
      amount: 	amount.to_f, 
      total: 		(someone.wallet_total).to_f + amount.to_f, 
			user_id: 	someone.id
		)

		# 财务扣款
		WalletLog.create!(
			transfer: 1, state: 1, strategy_result_id: id,
      amount: 	amount.to_f, 
      total: 		(acct.wallet_total).to_f - amount.to_f, 
			user_id: 	acct.id
		)
	end

end
